<template>
  <div>
    <!-- 回到顶部按钮 -->
    <button
      v-if="isVisible"
      @click="scrollToTop"
      :class="[
        position,
        'fixed rounded-sm shadow-lg animate__animated duration-700 animate__fadeInUp  text-gray-800 hover:bg-gray-100 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700'
      ]"
    >
      <My-svg-icon class="w-3 h-3" name="backTop"></My-svg-icon>
    </button>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps } from 'vue'
const props = defineProps({
  position: {
    type: String,
    default: 'bottom-4 right-6 '
  },
  showOffsetY: {
    type: Number,
    default: 400
  }
})
const isVisible = ref(false) // 控制按钮显示与否
let rafId = null

// 检查滚动位置
const checkScrollPosition = () => {
  const scrollTop = window.scrollY || document.documentElement.scrollTop
  isVisible.value = scrollTop > props.showOffsetY
}
// 平滑滚动到顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}
// 优化监听
const optimizedCheck = () => {
  if (!rafId) {
    rafId = requestAnimationFrame(() => {
      checkScrollPosition()
      rafId = null
    })
  }
}

// 生命周期管理
onMounted(() => {
  window.addEventListener('scroll', optimizedCheck)
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', optimizedCheck)
  if (rafId) cancelAnimationFrame(rafId)
})
</script>

<style scoped>
/* 自定义默认样式 */
</style>
